package com.joymart.product.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.joymart.dictionary.Dictionary;
import com.joymart.dictionary.DictionaryService;
import com.joymart.product.model.Product;
import com.joymart.product.service.ProductService;
import com.joymart.product.service.StockService;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
public class ProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private StockService stockService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private DictionaryService dictionaryService;

    @GetMapping("/products/{productId}")
    public Object productDetails(@PathVariable String productId) {
        Product product = productService.findByIdFromCache(productId);
        Map map = objectMapper.convertValue(product, Map.class);
        fillCategoryNames(map,product);
        map.put("stock", stockService.getCurrentStock(productId));
        return map;
    }

    @GetMapping("/products")
    public List<Map> getAll(){
        return productService
                .findOnMarketProductIds()
                .stream()
                .map(productService::findByIdFromCache)
                .map(product ->{
                    Map map = objectMapper.convertValue(product, Map.class);
                    fillCategoryNames(map,product);
                    return map;
                })
                .peek(map->map.put("stock", stockService.getCurrentStock(map.get("id").toString())))
                .collect(Collectors.toUnmodifiableList());
    }


    private void fillCategoryNames(Map map, Product product) {
        JSONArray categories = product.getMeta().has("categories") ? product.getMeta().getJSONArray("categories") : new JSONArray();
        Dictionary productCategoryDict = dictionaryService.findByName("product_category");
        List<String> categoryNames = new ArrayList<>();
        categories.forEach(category -> categoryNames.add(productCategoryDict.getItemText((String) category)));
        map.put("categoryNames",categoryNames);
    }
}
